package com.yiyi.credit.manage.abutment.common.utils;

import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;


public class BigDecimalUtil {

    public static final int SCALE = 2;


    public static final int MORE = 1;


    public static final int LESS = -1;


    public static final int EQUAL = 0;


    public static int compareTo(BigDecimal a, BigDecimal b) {
        if (a == null) {
            return LESS;
        } else if (b == null) {
            return MORE;
        } else if (a == null && b == null) {
            return EQUAL;
        } else {
            return a.compareTo(b);
        }
    }


    public static BigDecimal subtract(BigDecimal v1, BigDecimal v2) {
        return v1.subtract(v2);
    }


    public static BigDecimal add(BigDecimal v1, BigDecimal v2) {
        v1 = ObjectUtils.isEmpty(v1) ? new BigDecimal(0) : v1;
        v2 = ObjectUtils.isEmpty(v2) ? new BigDecimal(0) : v2;
        return v1.add(v2);
    }


    public static BigDecimal roundAdd(BigDecimal v1, BigDecimal v2, int n) {
        v1 = ObjectUtils.isEmpty(v1) ? new BigDecimal(0) : v1;
        v2 = ObjectUtils.isEmpty(v2) ? new BigDecimal(0) : v2;
        return v1.add(v2).setScale(n, RoundingMode.HALF_UP);
    }


    public static BigDecimal roundScale(BigDecimal a, int n) {
        return a.setScale(n, BigDecimal.ROUND_HALF_UP);
    }


    public static BigDecimal roundDownScale(BigDecimal a, int n) {
        return a.setScale(n, BigDecimal.ROUND_DOWN);
    }


    public static BigDecimal multiply(BigDecimal a, BigDecimal b, int n) {
        return a.multiply(b).setScale(n, RoundingMode.DOWN);
    }


    public static BigDecimal simpleMultiply(BigDecimal a, BigDecimal b) {
        return a.multiply(b);
    }


    public static BigDecimal roundMultiply(BigDecimal a, BigDecimal b, int n) {
        return a.multiply(b).setScale(n, RoundingMode.HALF_UP);
    }

    public static BigDecimal divide(BigDecimal a, BigDecimal b, int n) {
        return a.divide(b, n, RoundingMode.DOWN);
    }


    public static BigDecimal simpleDivide(BigDecimal a, BigDecimal b) {
        return a.divide(b);
    }


    public static BigDecimal roundDivide(BigDecimal a, BigDecimal b, int n) {
        return a.divide(b, n, BigDecimal.ROUND_HALF_UP);
    }


    public static BigDecimal retroposition(BigDecimal a, int n) {
        return a.movePointLeft(n);
    }

    public static BigDecimal valueOf(String value) {
        BigDecimal bigDecimal;
        if (StringUtil.isDouble(value)) {
            bigDecimal = new BigDecimal(value);
        } else {
            bigDecimal = BigDecimal.ZERO;
        }

        return bigDecimal;
    }

    public static BigDecimal min(BigDecimal b1, BigDecimal b2) {
        return b1.compareTo(b2) < 0 ? b1 : b2;
    }

    public static BigDecimal max(BigDecimal b1, BigDecimal b2) {
        return b1.compareTo(b2) < 0 ? b2 : b1;
    }

}
